<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Fenxiao extends ORM {
    public static function get_consume_amount($mid)
    {
        $orderList=DB::query(Database::SELECT,"select * from sline_member_order where memberid='$mid' and (status=2 or status=5)")->execute()->as_array();
        $amount=0;
        foreach($orderList as $row)
        {
            $amount+=Model_Member_Order::get_payed_amount($row);
        }
        return $amount;
    }
    //获取上级分销会员
    public static function get_ancestor_fenxiao($mid,$grade=1)
    {
        if(empty($grade) || $grade==1)
        {
            $model = ORM::factory('fenxiao')->where('memberid', '=', $mid)->find();
            if ($model->loaded())
            {
                $fenxiao=ORM::factory('fenxiao')->where('fxcode','=',$model->fxpcode)->find();
                if($fenxiao->loaded())
                    return $fenxiao->as_array();
            }
            else
                return null;
        }
        if($grade==2)
        {
            $firstFenxiao=self::get_ancestor_fenxiao($mid,1);
            if(empty($firstFenxiao))
                return null;
            return self::get_ancestor_fenxiao($firstFenxiao['memberid'],1);
        }
        if($grade==3)
        {
            $firstFenxiao=self::get_ancestor_fenxiao($mid,2);
            if(empty($firstFenxiao))
                return null;
            return self::get_ancestor_fenxiao($firstFenxiao['memberid'],1);
        }
    }

    //获取可分销的产品列表
    public static function get_fenxiao_product()
    {
        $result = DB::select()->from('model')
            
            ->where('is_fenxiao','=',1)
            ->and_where('is_showable','=',1)
            ->and_where('is_orderable','=',1)
            ->or_where('id','>',199)
            ->execute()->as_array();

        return $result;
    }

    //获取下级分销商的分享代码
    public static function get_sub_fxcode($fxcode,$type)
    {

        if(empty($type) ||$type==1) {
            $sql="select fxcode from sline_fenxiao where fxpcode='{$fxcode}'";
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $arr=array();
            foreach($list as $v)
            {
                $arr[]=$v['fxcode'];
            }
            return empty($arr)?null:$arr;
        }
        if($type==2)
        {
            $fxcodeArr=self::get_sub_fxcode($fxcode,0);
            if(empty($fxcodeArr))
                return null;
            foreach($fxcodeArr as &$v)
            {
                $v="'".$v."'";
            }
            $sql="select fxcode from sline_fenxiao where fxpcode in (".implode(',',$fxcodeArr).")";
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $arr=array();
            foreach($list as $v)
            {
                $arr[]=$v['fxcode'];
            }
            return empty($arr)?null:$arr;
        }
        if($type==3)
        {
            $fxcodeArr=self::get_sub_fxcode($fxcode,2);
            if(empty($fxcodeArr))
                return null;
            foreach($fxcodeArr as &$v)
            {
                $v="'".$v."'";
            }
            $sql="select fxcode from sline_fenxiao where fxpcode in (".implode(',',$fxcodeArr).")";
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $arr=array();
            foreach($list as $v)
            {
                $arr[]=$v['fxcode'];
            }
            return empty($arr)?null:$arr;
        }

    }
    //获取下级会员，$is_only表示是否仅获取当前级别的会员
    public static function get_sub_mids($mid,$rank=0,$is_only=false)
    {
        $fxModel=ORM::factory('fenxiao')->where('memberid','=',$mid)->find();
        if(!$fxModel->loaded())
        {
            return null;
        }
        $fxcode=$fxModel->fxcode;
        $first=self::get_sub_fxcode($fxcode,1);
        $second=$rank==0||$rank>=2?self::get_sub_fxcode($fxcode,2):null;
        $third=$rank==0||$rank==3?self::get_sub_fxcode($fxcode,3):null;
        $arr=array();
        if($is_only && $rank!=0)
        {
            switch($rank)
            {
                case 1:
                    $arr = $first;
                    break;
                case 2:
                    $arr = $second;
                    break;
                case 3:
                    $arr = $third;
                    break;
            }
        }
        else
        {
            if (!empty($first))
                $arr = array_merge($arr, $first);
            if (!empty($second))
                $arr = array_merge($arr, $second);
            if (!empty($third))
                $arr = array_merge($arr, $third);
        }
        if (count($arr) == 0)
        {
            return null;
        }



        foreach($arr as &$v)
        {
            $v="'".$v."'";
        }
        $w="where fxcode in (".implode(',',$arr).")";
        $sql="select memberid from sline_fenxiao {$w}";
        $memberidArr=DB::query(Database::SELECT,$sql)->execute()->as_array();
        $mids=array();
        foreach($memberidArr as $v)
        {
            $mids[]=$v['memberid'];
        }
        return $mids;
    }




    public static function joinus($mid,$fxcode='')
    {
        // 会员id必须大于零
        $check_member = Model_Member::get_member_byid($mid);
        if(!$check_member || !isset($check_member['mid']))
        {
            return false;
        }
        $model=ORM::factory('fenxiao')->where('memberid','=',$mid)->find();
        if($model->loaded() && $model->status!=-1)
            return true;
        $code='';
        while(true) {
            $code=self::gene_code();
            $count = ORM::factory('fenxiao')->where('fxcode', '=', $code)->count_all();
            if($count<=0)
                break;
        }
        if($model->loaded())
        {
            $model->status=0;
            $model->fxjointime = time();
        }else {
            $model->memberid = $mid;
            $model->fxpcode  = $fxcode ? $fxcode : '';
            $model->fxjointime = time();
            $model->fxamount = 0;
            $model->fxcode = $code;
            $model->fxrankid = self::get_rankid($mid);
        }
        $model->save();
        if($model->saved())
        {
             //成为分销商模板通知.
            if(St_Functions::is_normal_app_install('template_msg') || class_exists('Model_Wxmsg'))
            {
                // Model_Wxmsg::fenxiao_be_distributor($mid);
            }
            return true;
        }
        else
        {
            return false;
        }

    }
    public static function gene_code()
    {
        $str="0123456789abcdefghijklmnpqrstuvwxyz";
        $len=strlen($str);
        $number=8;
        $code='';
        for($i=0;$i<$number;$i++)
        {
            $code.=$str[mt_rand(0,$len-1)];
        }
        $num=ORM::factory('fenxiao')->where('fxcode','=',$code)->count_all();
        return $code;
    }
    //获取已提现总额
    public static function get_withdrawed_amount($mid)
    {
        $arr=DB::query(Database::SELECT,"select sum(ifnull(withdrawamount,0)) as amount from sline_fenxiao_withdraw where memberid={$mid} and status=1")->execute()->as_array();
        if(!empty($arr) &&!empty($arr[0]['amount']))
            return $arr[0]['amount'];
        return 0;
    }
    public static function check_fenxiao($mid,$redirect=true)
    {
        $fxModel=ORM::factory('fenxiao')->where('memberid','=',$mid)->find();
        $memberModel=ORM::factory('member',$mid);
        if(!$fxModel->loaded() || $fxModel->status==-1)
        {
            if(!$redirect)
                return false;
            Request::current()->redirect('fenxiao/jieshao/joinus');
            return;
        }
        $autoverify=Model_Fenxiao_Config::get_val('cfg_fenxiao_autoverify');

        if($fxModel->status==0 && $autoverify==1)
        {
            Request::current()->redirect('fenxiao/jieshao/joinus');
            return;
        }
        if($fxModel->status==0 && $autoverify==0)
        {
            Request::current()->redirect('fenxiao/joinverifying');
            return;
        }
        if($fxModel->status==2)
        {
            Request::current()->redirect('fenxiao/joinrefused');
            return;
        }

        if($fxModel->isfrozen==0)
        {
            $autofreeze=Model_Fenxiao_Config::get_val('cfg_fenxiao_autofreeze');
            $freezeduration=floatval(Model_Fenxiao_Config::get_val('cfg_fenxiao_freeze_duration'));
            $curtime=time();
            if($autofreeze==1&&$freezeduration>0&& $fxModel->fxlogintime>0)
            {
                $durationSeconds=$freezeduration*3600;
                if($fxModel->fxlogintime+$durationSeconds<$curtime)
                {
                    $fxModel->isfrozen=1;
                }
            }
            if($fxModel->isfrozen==0)
                $fxModel->fxlogintime=$curtime;
            $fxModel->save();
        }
        if($fxModel->isfrozen==1)
        {

            Request::current()->redirect('fenxiao/joinfrozen');
            return;
        }
        return $fxModel->as_array();
    }

    public static function save_fxcode()
    {

        $fxcode=$_GET['fxcode'];
        if(!empty($fxcode))
            Common::session('fxcode',$fxcode);
        $third_mid = Common::session('third_mid');
        if(!empty($third_mid))
        {
            Plugin_Core_Factory::factory()->add_listener('on_member_register', ORM::factory('member', $third_mid)->as_array())->execute();
            Common::session('third_mid',null);
        }
    }

    public static function get_fx_url()
    {
        $member = Model_Member_Login::check_login_info();
        if (empty($member))
            return null;
        $fenxiaoModel = ORM::factory('fenxiao')->where('memberid', '=', $member['mid'])->find();
        if (!$fenxiaoModel->loaded())
            return null;
        $fenxiao=$fenxiaoModel->as_array();
        $fxurl= St_Functions::is_SSL()? 'https://': 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?fxcode='.$fenxiao['fxcode'];
        $fxurl=urlencode($fxurl);
        return $fxurl;
    }
    public static function is_installed()
    {
        return St_Functions::is_normal_app_install('mobiledistribution');

    }

    //获取上级分销商信息
    public static function get_ancestor_fenxiao_info($mid,$grade=1)
    {
        if(empty($grade) || $grade==1)
        {
            $model = ORM::factory('fenxiao')->where('memberid', '=', $mid)->find();
            if ($model->loaded())
            {
                $fenxiao=ORM::factory('fenxiao')->where('fxcode','=',$model->fxpcode)->find();
                if($fenxiao->loaded())
                    return $fenxiao->as_array();
            }
            else
                return null;
        }
        if($grade==2)
        {
            $firstFenxiao=self::get_ancestor_fenxiao_info($mid,1);
            if(empty($firstFenxiao))
                return null;
            return self::get_ancestor_fenxiao_info($firstFenxiao['memberid'],1);
        }
        if($grade==3)
        {
            $firstFenxiao=self::get_ancestor_fenxiao_info($mid,2);
            if(empty($firstFenxiao))
                return null;
            return self::get_ancestor_fenxiao_info($firstFenxiao['memberid'],1);
        }
    }

    //判断当前会员是否为分销商
    public static function is_fenxiao($isonly=false)
    {

        try {
            $member = Model_Member_Login::check_login_info();
            if (empty($member))
                throw new Exception();
            $fenxiaoModel = ORM::factory('fenxiao')->where('memberid', '=', $member['mid'])->find();
            if (!$fenxiaoModel->loaded())
                throw new Exception();
            $fenxiao=$fenxiaoModel->as_array();

            if(($fenxiao['status']!=1 || $fenxiao['isfrozen']==1)&& !$isonly)
                throw new Exception();
            $fxurl=St_Functions::is_SSL() ? 'https://': 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?fxcode='.$fenxiao['fxcode'];
            return $fenxiao;
        }
        catch(Exception $excep)
        {
            $fxcode=$_GET['fxcode'];
            if(!empty($fxcode))
                Common::session('fxcode',$fxcode);
            return false;
        }
    }

    //获取返佣信息
    public static function get_commission_info($typeid,$productid,$groupid)
    {
        $commissiontype=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$typeid,$groupid);

        $rateArr=array();
        $cashArr=array();
        if($commissiontype==1) {
            $rateArr = self::get_commission_rate($typeid, $productid,$groupid);
        }
        else if($commissiontype==2)
        {
            $rateArr = self::get_commission_rate_platform($typeid, $productid,$groupid);
        }
        else {
            $cashArr = self::get_commission_cash($typeid, $productid,$groupid);
        }

        return array('commission_type'=>$commissiontype,'rate_arr'=>$rateArr,'cash_arr'=>$cashArr);

    }

    //获取某一产品的返佣比例
    public static  function get_commission_rate($typeid,$productid,$groupid=0)
    {
        $groupid = empty($groupid)?0:$groupid;
        $configList=ORM::factory('fenxiao_config')->and_where('groupid','=',$groupid)->get_all();
        $first=0;
        $second=0;
        $third=0;
        $last = 0;//表示分销商自身

        //先检测产品是否有单独设置佣金配置
        $ratioModel=ORM::factory('fenxiao_ratio')->where('typeid','=',$typeid)->and_where('productid','=',$productid)->and_where('groupid','=',$groupid)->find();
        if($ratioModel->loaded())
        {
            $last = floatval($ratioModel->fxratio);
            $last = empty($last)?0:$last/100;

            $first=floatval($ratioModel->fxratio1);
            $first=empty($first)?0:$first/100;

            $second=floatval($ratioModel->fxratio2);
            $second=empty($second)?0:$second/100;

            $third=floatval($ratioModel->fxratio3);
            $third=empty($third)?0:$third/100;
        }
        //如果产品没有单独佣金配置则使用全局配置
        foreach($configList as $k=>$v)
        {
            if($v['varname']=='cfg_fenxiao_first_ratio_'.$typeid && empty($first))
            {
                $val=floatval($v['value']);
                $first=empty($val)?0:$val/100;
            }
            if($v['varname']=='cfg_fenxiao_second_ratio_'.$typeid  && empty($second))
            {
                $val=floatval($v['value']);
                $second=empty($val)?0:$val/100;
            }
            if($v['varname']=='cfg_fenxiao_third_ratio_'.$typeid && empty($third))
            {
                $val=floatval($v['value']);
                $third=empty($val)?0:$val/100;
            }
            if($v['varname']=='cfg_fenxiao_self_ratio_'.$typeid && empty($last))
            {
                $val=floatval($v['value']);
                $last=empty($val)?0:$val/100;
            }

        }
        return array($first,$second,$third,$last);
    }

    //获取按平台佣金反佣时的 佣金信息
    public static function get_commission_rate_platform($typeid,$productid,$groupid=0)
    {
        $groupid = empty($groupid)?0:$groupid;
        $configList=ORM::factory('fenxiao_config')->and_where('groupid','=',$groupid)->get_all();
        $first=0;
        $second=0;
        $third=0;
        $last = 0;//表示分销商自身

        $ratioModel=ORM::factory('fenxiao_ratio')
            ->where('typeid','=',$typeid)
            ->and_where('productid','=',$productid)
            ->and_where('groupid','=',$groupid)
            ->find();
        if($ratioModel->loaded())
        {
            $last = floatval($ratioModel->pm_fxratio);
            $last = empty($last)?0:$last/100;

            $first=floatval($ratioModel->pm_fxratio1);
            $first=empty($first)?0:$first/100;

            $second=floatval($ratioModel->pm_fxratio2);
            $second=empty($second)?0:$second/100;

            $third=floatval($ratioModel->pm_fxratio3);
            $third=empty($third)?0:$third/100;
        }

        foreach($configList as $k=>$v)
        {
            if($v['varname']=='cfg_fenxiao_first_platform_ratio_'.$typeid && empty($first))
            {
                $val=floatval($v['value']);
                $first=empty($val)?0:$val/100;
            }
            if($v['varname']=='cfg_fenxiao_second_platform_ratio_'.$typeid  && empty($second))
            {
                $val=floatval($v['value']);
                $second=empty($val)?0:$val/100;
            }
            if($v['varname']=='cfg_fenxiao_third_platform_ratio_'.$typeid && empty($third))
            {
                $val=floatval($v['value']);
                $third=empty($val)?0:$val/100;
            }
            if($v['varname']=='cfg_fenxiao_self_platform_ratio_'.$typeid && empty($last))
            {
                $val=floatval($v['value']);
                $last=empty($val)?0:$val/100;
            }

        }
        return array($first,$second,$third,$last);
    }
    //获取某一产品的返佣金额, 已弃用， 使用get_commission_cash_line
    public static function get_commission_cash($typeid,$productid,$groupid=0)
    {
        $groupid = empty($groupid)?0:$groupid;
        $configList=ORM::factory('fenxiao_config')->and_where('groupid','=',$groupid)->get_all();
        $first=0;
        $second=0;
        $third=0;
        $last = 0;

        $ratioModel=ORM::factory('fenxiao_ratio')->where('typeid','=',$typeid)->and_where('productid','=',$productid)->and_where('groupid','=',$groupid)->find();
        if($ratioModel->loaded())
        {
            $first=floatval($ratioModel->cash1);
            $first=empty($first)?0:$first;

            $second=floatval($ratioModel->cash2);
            $second=empty($second)?0:$second;

            $third=floatval($ratioModel->cash3);
            $third=empty($third)?0:$third;

            $last = floatval($ratioModel->cash);
            $last = empty($last)?0:$last;
        }

        foreach($configList as $k=>$v)
        {
            if($v['varname']=='cfg_fenxiao_first_cash_'.$typeid && empty($first))
            {
                $val=floatval($v['value']);
                $first=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_second_cash_'.$typeid  && empty($second))
            {
                $val=floatval($v['value']);
                $second=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_third_cash_'.$typeid && empty($third))
            {
                $val=floatval($v['value']);
                $third=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_self_cash_'.$typeid && empty($last))
            {
                $val=floatval($v['value']);
                $last=empty($val)?0:$val;
            }
        }
        return array($first,$second,$third,$last);
    }

    //获取mid2属于mid1的几第级下级
    public static function get_rank($mid1,$mid2)
    {
        $fxcode1 = DB::select('fxcode')->from('fenxiao')->where('memberid','=',$mid1)->execute()->get('fxcode');
        $fxcode2 = DB::select('fxcode')->from('fenxiao')->where('memberid','=',$mid2)->execute()->get('fxcode');

        $curcode = $fxcode2;
        $index=1;
        while(true)
        {
            $pcode =  DB::select('fxpcode')->from('fenxiao')->where('fxcode','=',$curcode)->execute()->get('fxpcode');
            if(empty($pcode))
            {
                return 0;
                break;
            }
            if($pcode==$fxcode1)
            {
                return $index;
            }
            if($index>4)
           {
                return 0;
            }
            $index++;
            $curcode = $pcode;
        }
        return $index;
    }

    //获取产品价格
    public static  function get_price($typeid,$productid)
    {
        $model_info = DB::select()->from('model')->where('id','=',$typeid)->execute()->current();
        $maintable = $model_info['maintable'];
        $letter_arr = explode('_',$maintable);
        foreach($letter_arr as &$letter)
        {
            $letter = ucfirst($letter);
        }
        $class_name='Model_'.implode('_',$letter_arr);
        $price = 0;
        if(class_exists($class_name)&& method_exists($class_name,'get_minprice') )
        {
           $price = call_user_func(array($class_name, 'get_minprice'),$productid);
        }
        if(is_array($price))
        {
            $price = $price['price'];
        }
        return $price;
    }
    //获取下级订单数量
    public static function get_sub_order_num($memberid,$level=0,$order_status=null)
    {
        $sub_mids = self::get_sub_mids($memberid,$level);
        if(empty($sub_mids))
        {
            return 0;
        }
        $w =" where memberid in (".implode(',',$sub_mids).") ";
        if($order_status!==null)
        {
            $w.= " and (status={$order_status} or status=8) ";
        }
        $sql = " select count(*) as num from sline_member_order {$w}";
        $num = DB::query(Database::SELECT,$sql)->execute()->get('num');
        return $num;
    }


    //获取下级订单数量
    public static function new_get_sub_order_num($memberid,$level=0,$order_status=null)
    {
        $all_fenxiandata = Db::query(1,"select order_id from sline_fenxiao_data where memberid1={$memberid} or memberid2={$memberid} or memberid3={$memberid}")->execute()->as_array();
        if(empty($all_fenxiandata))
        {
            return 0;
        }
        $all_fenxiandata = array_column($all_fenxiandata,'order_id');
        $w =" where id in (".implode(',',$all_fenxiandata).") ";
        if($order_status!==null)
        {
            $w.= " and (status={$order_status} or status=8) ";
        }
        $sql = " select count(*) as num from sline_member_order {$w}";
        $num = DB::query(Database::SELECT,$sql)->execute()->get('num');
        return $num;
    }

    //获取会员等级
    public static function get_rankid($memberid)
    {
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $order_num = self::get_sub_order_num($memberid,$level_num,5);
        $sql = "select id from sline_fenxiao_rank where min_order_num<={$order_num} and (max_order_num=0 || max_order_num>={$order_num})";
        $rankid =DB::query(Database::SELECT,$sql)->execute()->get('id');
        return $rankid;
    }

    //重新计算所有会员等级,0表示更新所有会员等级
    public static function update_member_rank($memberid=false)
    {
        $query = DB::select('memberid')->from('fenxiao');
        if($memberid)
        {
            $query->where('memberid','=',$memberid);
        }
        $member_list = $query->execute()->as_array();
        foreach($member_list as $row)
        {
            $rankid = self::get_rankid($row['memberid']);
            $rankid = empty($rankid)?0:$rankid;
            DB::update('fenxiao')->set(array('fxrankid'=>$rankid))->where('memberid','=',$row['memberid'])->execute();
        }

    }
    //获取反佣总和
    public static  function get_total_profit($memberid)
    {
        $result = DB::query(Database::SELECT,"select sum(amount) as total from sline_fenxiao_record where memberid='{$memberid}' and type=0")->execute()->current();
        return empty($result['total'])?0:$result['total'];
    }

    public static function new_get_sub_order_totalprice($memberid,$level=0,$order_status=null)
    {
        $all_fenxiandata = Db::query(1,"select order_id from sline_fenxiao_data where memberid1={$memberid} or memberid2={$memberid} or memberid3={$memberid}")->execute()->as_array();
        if(empty($all_fenxiandata))
        {
            return 0;
        }
        $all_fenxiandata = array_column($all_fenxiandata,'order_id');
        $w =" where id in (".implode(',',$all_fenxiandata).") ";
        if($order_status!==null)
        {
            $w.= " and status={$order_status} or status=8";
        }
        $sql = " select * from sline_member_order {$w}";
        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        $totalprice = 0;
        foreach($list as $row)
        {
            $totalprice+= Model_Member_Order::order_total_price($row['id'],$row);
        }
        return $totalprice;
    }

    public static function get_sub_order_totalprice($memberid,$level=0,$order_status=null)
    {
        $sub_mids = self::get_sub_mids($memberid,$level);
        if(empty($sub_mids))
        {
            return 0;
        }
        $w =" where memberid in (".implode(',',$sub_mids).") ";
        if($order_status!==null)
        {
            $w.= " and status={$order_status} or status=8 ";
        }
        $sql = " select * from sline_member_order {$w}";
        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        $totalprice = 0;
        foreach($list as $row)
        {
            $totalprice+= Model_Member_Order::order_total_price($row['id'],$row);
        }
        return $totalprice;
    }

    //获取下级订单
    public static function get_sub_orders($memberid,$level=0,$order_status=null)
    {
        $sub_mids = self::get_sub_mids($memberid,$level);


        if(empty($sub_mids))
        {
            return 0;
        }
        $w =" where memberid in (".implode(',',$sub_mids).") ";

        if($order_status!==null)
        {
            $w.= " and status={$order_status} ";
        }
        $sql = " select * from sline_member_order {$w}";
        $list = DB::query(Database::SELECT,$sql)->execute()->as_array();
        return $list;
    }

    //邀请
    public static function invite($mid,$fxpcode)
    {
        // 会员id必须大于零
        $check_member = Model_Member::get_member_byid($mid);
        if(!isset($check_member['mid']))
        {
            return false;
        }

        if(!$fxpcode)
        {
            return false;
        }
        // 检查分销商是否存在
        $pfx = DB::select()->from("fenxiao")->where("fxcode","=",$fxpcode)->and_where('memberid','>',0)->execute()->current();
        if(!$pfx)
        {
            return false;
        }

        $model=ORM::factory('fenxiao')->where('memberid','=',$mid)->find();
        if($model->loaded())
            return true;
        $code='';
        while(true) {
            $code=self::gene_code();
            $count = ORM::factory('fenxiao')->where('fxcode', '=', $code)->count_all();
            if($count<=0)
                break;
        }
        $curtime = time();
        $fenxiao_orderautopassed = Model_Fenxiao_Config::get_val('cfg_fenxiao_orderautopassed');
        $status = $fenxiao_orderautopassed==1?1:-1;
        $model->memberid=$mid;
        $model->fxjointime=$curtime;
        $model->fxamount=0;
        $model->fxcode=$code;
        $model->status=$status;
        if($status==1)
        {
            $fxrankid = Model_Fenxiao::get_rankid($mid);
            $model->fxrankid=$fxrankid;
            $model->verifytime = $curtime;
        }
        $model->fxpcode= $fxpcode;
        $model->save();
        if($model->saved())
            return true;
        else
            return false;
    }


    public static function dowload_picture($url)
    {
        return self::download($url);

           include_once(PUBLICPATH.'/vendor/httpdown.class.php');

            if(strpos($url,'//')==0)
            {
                $url = 'http:'.$url;
            }

            if(strpos($url,'http://')===false && strpos($url,'https://')===false && 0)
            {
                return $url;
            }
            if(!stristr($url,$GLOBALS['cfg_basehost']))
            {

                $htd = new HttpDown();//实例化
                $htd->OpenUrl($url);

                $sparr = Array("image peg", "image/jpeg", "image/gif", "image/png", "image/xpng", "image/wbmp");
                if(!in_array($htd->GetHead("content-type"),$sparr))
                {
                    return '';
                }
                else
                {

                    $date=date("Ymd");
                    $name=date("YmdHis").rand(1,50);
                    $path=UPLOADPATH."/main/allimg/";


                    $url=$path.$date."/";
                    $imgUrl = $url.$name;


                    //创建路径
                    if(!file_exists($url))
                    {
                        mkdir($url);
                    }
                    $itype = $htd->GetHead("content-type");

                    if($itype=="image/gif")
                    {
                        $itype = '.gif';
                    }
                    else if($itype=="image/png")
                    {
                        $itype = '.png';
                    }
                    else if($itype=="image/wbmp")
                    {
                        $itype = '.bmp';
                    }
                    else
                    {
                        $itype = '.jpg';
                    }
                    $fileurl = $imgUrl.$itype;
                    $ok = $htd->SaveToBin($fileurl);
                    $litpic = $fileurl;

                    $litpic=str_replace(BASEPATH,'',$litpic);//去掉头
                    $litpic=str_replace('\\','/',$litpic);
                }



            }
            else
            {
                $litpic=$url;
            }
            return $litpic;
    }

    //获取关键词的下级所有会员
    public static function get_keyword_sub_mids($keyword)
    {
        $list = DB::query(Database::SELECT,"select mid from sline_member where mobile like '%{$keyword}%' or email like '%{$keyword}%' or nickname like '%{$keyword}%'")->execute()->as_array();
        $all_mids = array();
        foreach($list as $row)
        {
            $fxcode = DB::select('fxcode')->from('fenxiao')->where('memberid','=',$row['mid'])->execute()->get('fxcode');
            $sub_mids = DB::select('memberid')->from('fenxiao')->where('fxpcode','=',$fxcode)->execute()->as_array();
            foreach($sub_mids as $v)
            {
                $all_mids[] = $v['memberid'];
            }
        }
        return $all_mids;
    }

    public static function get_commission_info_line($typeid,$productid,$groupid)
    {
        $commissiontype=Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$typeid,$groupid);

        $rateArr=array();
        $cashArr=array();
        //cfg_fenxiao_commission_type 1:按订单金额百分比 0:现金 2:平台收入百分比
        if($commissiontype==1) {
            $rateArr = self::get_commission_rate($typeid, $productid,$groupid);
        }
        else if($commissiontype==2)
        {
            $pmRateArr = self::get_commission_rate_platform($typeid,$productid,$groupid);
        }
        else {
            $cashArr = self::get_commission_cash_line($typeid, $productid,$groupid);
        }

        return array('commission_type'=>$commissiontype,'rate_arr'=>$rateArr,'cash_arr'=>$cashArr,'pm_rate_arr'=>$pmRateArr);

    }
    //获取某一产品的返佣金额
    public static function get_commission_cash_line($typeid,$productid,$groupid=0)
    {
        $groupid = empty($groupid)?0:$groupid;
        $configList=ORM::factory('fenxiao_config')->and_where('groupid','=',$groupid)->get_all();
        $first=0;
        $first_old = 0;
        $first_child = 0;
        $first_people4 = 0;
        $first_people5 = 0;
        $first_people6 = 0;


        $second=0;
        $second_old = 0;
        $second_child = 0;
        $second_people4 = 0;
        $second_people5 = 0;
        $second_people6 = 0;

        $third=0;
        $third_old = 0;
        $third_child = 0;
        $third_people4 = 0;
        $third_people5 = 0;
        $third_people6 = 0;


        $last = 0;
        $last_old=0;
        $last_child=0;
        $last_people4 = 0;
        $last_people5 = 0;
        $last_people6 = 0;

        $ratioModel=ORM::factory('fenxiao_ratio')->where('typeid','=',$typeid)->and_where('productid','=',$productid)->and_where('groupid','=',$groupid)->find();
        if($ratioModel->loaded())
        {
            $first=floatval($ratioModel->cash1);
            $first=empty($first)?0:$first;
            $first_child=floatval($ratioModel->cash1_child);
            $first_child=empty($first_child)?0:$first_child;
            $first_old=floatval($ratioModel->cash1_old);
            $first_old=empty($first_old)?0:$first_old;

            $first_people4 = floatval($ratioModel->cash1_people4);
            $first_people5 = floatval($ratioModel->cash1_people5);
            $first_people6 = floatval($ratioModel->cash1_people6);



            $second=floatval($ratioModel->cash2);
            $second=empty($second)?0:$second;
            $second_child=floatval($ratioModel->cash2_child);
            $second_child=empty($second_child)?0:$second_child;
            $second_old=floatval($ratioModel->cash2_old);
            $second_old=empty($second_old)?0:$second_old;

            $second_people4 = floatval($ratioModel->cash2_people4);
            $second_people5 = floatval($ratioModel->cash2_people5);
            $second_people6 = floatval($ratioModel->cash2_people6);



            $third=floatval($ratioModel->cash3);
            $third=empty($third)?0:$third;
            $third_child=floatval($ratioModel->cash3_child);
            $third_child=empty($third_child)?0:$third_child;
            $third_old=floatval($ratioModel->cash3_old);
            $third_old=empty($third_old)?0:$third_old;

            $third_people4 = floatval($ratioModel->cash3_people4);
            $third_people5 = floatval($ratioModel->cash3_people5);
            $third_people6 = floatval($ratioModel->cash3_people6);


            $last = floatval($ratioModel->cash);
            $last = empty($last)?0:$last;
            $last_child=floatval($ratioModel->cash_child);
            $last_child=empty($last_child)?0:$last_child;
            $last_old=floatval($ratioModel->cash_old);
            $last_old=empty($last_old)?0:$last_old;

            $last_people4 = floatval($ratioModel->cash_people4);
            $last_people5 = floatval($ratioModel->cash_people5);
            $last_people6 = floatval($ratioModel->cash_people6);

        }


        foreach($configList as $k=>$v)
        {

            if($v['varname']=='cfg_fenxiao_first_cash_'.$typeid && (empty($first)|| $first==0))
            {

                $val=floatval($v['value']);
                $first=empty($val)?0:$val;

            }
            if($v['varname']=='cfg_fenxiao_first_cash_'.$typeid.'_old' && (empty($first_old)|| $first_old==0))
            {
                $val=floatval($v['value']);
                $first_old=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_first_cash_'.$typeid.'_child' && (empty($first_child)|| $first_child==0))
            {
                $val=floatval($v['value']);
                $first_child=empty($val)?0:$val;
            }
            
            if($v['varname']=='cfg_fenxiao_first_cash_'.$typeid.'_people4' && (empty($first_people4)|| $first_people4==0))
            {
                $val=floatval($v['value']);
                $first_people4=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_first_cash_'.$typeid.'_people5' && (empty($first_people5)|| $first_people5==0))
            {
                $val=floatval($v['value']);
                $first_people5=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_first_cash_'.$typeid.'_people6' && (empty($first_people6)|| $first_people6==0))
            {
                $val=floatval($v['value']);
                $first_people6=empty($val)?0:$val;
            }





            if($v['varname']=='cfg_fenxiao_second_cash_'.$typeid  && (empty($second) || $second==0))
            {
                $val=floatval($v['value']);
                $second=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_second_cash_'.$typeid.'_old' && (empty($second_old) || $second_old==0))
            {
                $val=floatval($v['value']);
                $second_old=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_second_cash_'.$typeid.'_child' && (empty($second_child) || $second_child==0))
            {
                $val=floatval($v['value']);
                $second_child=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_second_cash_'.$typeid.'_people4' && empty($second_people4))
            {
                $val=floatval($v['value']);
                $second_people4=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_second_cash_'.$typeid.'_people5' && empty($second_people5))
            {
                $val=floatval($v['value']);
                $second_people5=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_second_cash_'.$typeid.'_people6' && empty($second_people6))
            {
                $val=floatval($v['value']);
                $second_people6=empty($val)?0:$val;
            }





            if($v['varname']=='cfg_fenxiao_third_cash_'.$typeid && (empty($third) || $third==0))
            {
                $val=floatval($v['value']);
                $third=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_third_cash_'.$typeid.'_old' && (empty($third_old) || $third_old==0))
            {
                $val=floatval($v['value']);
                $third_old=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_third_cash_'.$typeid.'_child' && (empty($third_child) || $third_child==0))
            {
                $val=floatval($v['value']);
                $third_child=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_third_cash_'.$typeid.'_people4' && empty($third_people4))
            {
                $val=floatval($v['value']);
                $third_people4=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_third_cash_'.$typeid.'_people5' && empty($third_people5))
            {
                $val=floatval($v['value']);
                $third_people5=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_third_cash_'.$typeid.'_people6' && empty($third_people6))
            {
                $val=floatval($v['value']);
                $third_people6=empty($val)?0:$val;
            }




            if($v['varname']=='cfg_fenxiao_self_cash_'.$typeid && (empty($last)|| $last==0))
            {
                $val=floatval($v['value']);
                $last=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_self_cash_'.$typeid.'_old' && (empty($last_old)||$last_old==0))
            {
                $val=floatval($v['value']);
                $last_old=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_self_cash_'.$typeid.'_child' && (empty($last_child) || $last_child==0))
            {
                $val=floatval($v['value']);
                $last_child=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_self_cash_'.$typeid.'_people4' && empty($last_people4))
            {
                $val=floatval($v['value']);
                $last_people4=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_self_cash_'.$typeid.'_people5' && empty($last_people5))
            {
                $val=floatval($v['value']);
                $last_people5=empty($val)?0:$val;
            }
            if($v['varname']=='cfg_fenxiao_self_cash_'.$typeid.'_people6' && empty($last_people6))
            {
                $val=floatval($v['value']);
                $last_people6=empty($val)?0:$val;
            }

        }
        return array(
            0=>array('adult'=>$first,'old'=>$first_old,'child'=>$first_child,'people4'=>$first_people4,'people5'=>$first_people5,'people6'=>$first_people6),
            1=>array('adult'=>$second,'old'=>$second_old,'child'=>$second_child,'people4'=>$second_people4,'people5'=>$second_people5,'people6'=>$second_people6),
            2=>array('adult'=>$third,'old'=>$third_old,'child'=>$third_child,'people4'=>$third_people4,'people5'=>$third_people5,'people6'=>$third_people6),
            3=>array('adult'=>$last,'old'=>$last_old,'child'=>$last_child,'people4'=>$last_people4,'people5'=>$last_people5,'people6'=>$last_people6)
        );
    }

    //记录下单时产品的各项 信息
    public static function  book_data($ordersn,$order_info=null)
    {
        $order_info = empty($order_info)? Model_Member_Order::order_info($ordersn):$order_info;

        $cur_fenxiao_model=ORM::factory('fenxiao')->where('memberid','=',$order_info['memberid'])->find();
        //获取分销级别 2级 or 3级
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');

        if(!$cur_fenxiao_model->loaded())
        {
            $data_model = ORM::factory('fenxiao_data');
            $data_model->memberid = $order_info['memberid'];
            $data_model->order_id = $order_info['id'];
            $data_model->addtime = time();
            $data_model->fx_status = -2;
            $data_model->save();
            return;
        }
        //找出所有上级分销商
        $fenxiaoArr=array();
        $fenxiaoArr[]=Model_Fenxiao::get_ancestor_fenxiao_info($order_info['memberid'],1);
        $fenxiaoArr[]=Model_Fenxiao::get_ancestor_fenxiao_info($order_info['memberid'],2);
        if($level_num==0 || $level_num==3)
        {
            $fenxiaoArr[] = Model_Fenxiao::get_ancestor_fenxiao_info($order_info['memberid'], 3);
        }


        $data_model = ORM::factory('fenxiao_data');
        $data_model->memberid = $order_info['memberid'];
        $data_model->order_id = $order_info['id'];
        $data_model->groupid = $cur_fenxiao_model->fxgroupid;
        $data_model->fx_status = $cur_fenxiao_model->status;
        $data_model->addtime = time();
        $data = array();

        foreach($fenxiaoArr as $k=>$v) {
            $number = $k+1;
            if ($v) {
                $fenxiaoModel = ORM::factory('fenxiao', $v['id']);
                if ($fenxiaoModel->loaded())
                {

                    $commission_info = self::get_commission_info_line($order_info['typeid'], $order_info['productautoid'],$fenxiaoModel->fxgroupid);



                    $data['memberid'.$number]=$fenxiaoModel->memberid;
                    $data['groupid'.$number] = $fenxiaoModel->fxgroupid;
                    $data['type'.$number] = $commission_info['commission_type'];

                    if($commission_info['commission_type']==1)
                    {
                         $data['fxratio'.$number]=$commission_info['rate_arr'][$k];
                    }
                    else if($commission_info['commission_type']==2)
                    {
                        $data['pm_fxratio'.$number]=$commission_info['pm_rate_arr'][$k];
                    }
                    else
                    {
                        $cash_info = $commission_info['cash_arr'][$k];
                        if($order_info['typeid']==1)
                        {
                            $data['cash'.$number] = $cash_info['adult'];
                            $data['cash'.$number.'_old'] = $cash_info['old'];
                            $data['cash'.$number.'_child'] = $cash_info['child'];
                            $data['cash'.$number.'_people4'] = $cash_info['people4'];
                            $data['cash'.$number.'_people5'] = $cash_info['people5'];
                            $data['cash'.$number.'_people6'] = $cash_info['people6'];
                        }
                        else if($order_info['typeid'])
                        {
                            $data['cash'.$number] = $cash_info['adult'];
                        }
                    }
                }
            }
        }

        //自购佣金信息
        $commission_info = self::get_commission_info_line($order_info['typeid'], $order_info['productautoid'],$cur_fenxiao_model->fxgroupid);
        $data['type'] = $commission_info['commission_type'];
        if($commission_info['commission_type']==1)
        {
            $data['fxratio'] = array_pop($commission_info['rate_arr']);
        }
        else if($commission_info['commission_type']==2)
        {
            $data['pm_fxratio']=array_pop($commission_info['pm_rate_arr']);
        }
        else
        {
            $cash_info = array_pop($commission_info['cash_arr']);
            if($order_info['typeid']==1)
            {
                $data['cash'] = $cash_info['adult'];
                $data['cash_old'] = $cash_info['old'];
                $data['cash_child'] = $cash_info['child'];
                $data['cash_people4'] = $cash_info['people4'];
                $data['cash_people5'] = $cash_info['people5'];
                $data['cash_people6'] = $cash_info['people6'];
            }
            else
            {
                $data['cash'] = $cash_info['adult'];
            }
        }

        foreach($data as $key=>$val)
        {
            $data_model->$key=$val;
        }
        $data_model->save();
    }

    //获取订单的反佣金额
    public static function get_order_fenxiao_info($order)
    {
//        $order['platform_commission']=DB::select()->from('member_order_compute')->where('order_id','=',$order['id'])->execute()->current()['platform_commission'];
        $fenxiao_data = DB::select()->from('fenxiao_data')->where('order_id','=',$order['id'])->execute()->current();
        $cur_fenxiao_model=ORM::factory('fenxiao')->where('memberid','=',$order['memberid'])->find();
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');

        if(!$cur_fenxiao_model->loaded())
        {
            return null;
        }

        $fenxiaoArr=array();
        $fenxiaoArr[]=Model_Fenxiao::get_ancestor_fenxiao_info($order['memberid'],1);
        $fenxiaoArr[]=Model_Fenxiao::get_ancestor_fenxiao_info($order['memberid'],2);
        if($level_num==0 || $level_num==3)
        {
            $fenxiaoArr[] = Model_Fenxiao::get_ancestor_fenxiao_info($order['memberid'], 3);
        }

        $commission_info = array();
        //一级分销反佣
        foreach($fenxiaoArr as $k=>$v)
        {
            if ($v)
            {
                $number = $k+1;
                $fenxiaoModel = ORM::factory('fenxiao', $v['id']);
                if ($fenxiaoModel->loaded())
                {
                    if($fenxiaoModel->isfrozen==1)
                    {
                        continue;
                    }
                    //计算佣金
                    $payAmount = DB::select()->from('member_order_compute')->where("order_id={$order['id']}")->execute()->get('fx_top'.$number);
                    if($payAmount==0 ){
                        $payAmount = Model_Fenxiao_Commission::compute_commission($number, $fenxiao_data, $order, $order['platform_commission']);
                    }
                    $commission_info['commission' . $number] = $payAmount;
                }
            }
        }
        //自身返佣
        if($cur_fenxiao_model->status==1 && $cur_fenxiao_model->isfrozen!=1)
        {
            $payAmount = DB::select()->from('member_order_compute')->where("order_id={$order['id']}")->execute()->get('fx_self');
            if($payAmount==0 ){
                $payAmount = Model_Fenxiao_Commission::compute_commission('', $fenxiao_data, $order, $order['platform_commission']);
            }
            $commission_info['commission'] = $payAmount;
        }
        return empty($commission_info) || count($commission_info)==0?null:$commission_info;
    }

    public  static function download($url)
    {


        if(strpos($url,'//')===0)
        {
            $url = 'http:'.$url;
        }
        if(strpos($url,'http://')===false && strpos($url,'https://')===false)
        {
            return $url;
        }

        if(!stristr($url,$GLOBALS['cfg_basehost'])) {

            $date = date("Ymd");
            $name = date("YmdHis") . rand(1, 50);
            $name = preg_replace('/(\/)|(\/)|(\?)|(\#)|(\%)|(\&)|(\=)|(\.)|(\:)/i', '_',$url);
            $path = UPLOADPATH . "/main/allimg/fenxiao";
            if(!file_exists($path))
            {
                mkdir($path);
            }


            $file_base_url = $path .'/';

            if(!file_exists($file_base_url))
            {
                mkdir($file_base_url);
            }
            $imgUrl = $file_base_url . $name;

            $path_info = pathinfo($url);

            $itype = empty($path_info['extension']) ? 'jpg' : $path_info['extension'];


            $fileurl = $imgUrl . '.' . $itype;

            if(file_exists($fileurl))
            {
                $litpic=str_replace(BASEPATH,'',$fileurl);//去掉头
                $litpic=str_replace('\\','/',$litpic);
                return $litpic;
            }


            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
            $file = curl_exec($ch);
            $resource = fopen($fileurl, 'a');
            fwrite($resource, $file);
            fclose($resource);
            $errno = curl_errno($ch);
            curl_close($ch);

            $litpic=str_replace(BASEPATH,'',$fileurl);//去掉头
            $litpic=str_replace('\\','/',$litpic);
            if(empty($errno))
            {
                return $litpic;
            }
            else
            {
                return null;
            }
        }else{
            $img=str_replace($GLOBALS['cfg_basehost'].'/','',$url);
            return $img;
        }
    }


    public static function download_code($code_url)
    {
        $url =St_Client::get_http_protocol(). $GLOBALS['current_host'].$GLOBALS['cfg_public_url']."vendor/qrcode/make.php?param={$code_url}";
        $date = date("Ymd");
        $name = preg_replace('/(\/)|(\/)|(\?)|(\#)|(\%)|(\&)|(\=)|(\.)|(\:)/i', '_',$code_url);
      // $name = date("YmdHis") . rand(1, 50);
        $path = UPLOADPATH . "/main/allimg/";

        $file_base_url = $path . $date . "/";

        if(!file_exists($file_base_url))
        {
            mkdir($file_base_url);
        }
        $imgUrl = $file_base_url . $name;
        $path_info = pathinfo($url);
        $itype = 'png';
        $fileurl = $imgUrl . '.' . $itype;

        if(file_exists($fileurl))
        {
            $litpic=str_replace(BASEPATH,'',$fileurl);//去掉头
            $litpic=str_replace('\\','/',$litpic);
            return $litpic;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        $file = curl_exec($ch);
        $resource = fopen($fileurl, 'a');
        fwrite($resource, $file);
        fclose($resource);
        $errno = curl_errno($ch);
        curl_close($ch);

        $litpic=str_replace(BASEPATH,'',$fileurl);//去掉头
        $litpic=str_replace('\\','/',$litpic);
        if(empty($errno))
        {
            return $litpic;
        }
        else
        {
            return null;
        }
    }

    //分销中心产品排序比较函数
    public static function product_order_cmp($a,$b)
    {
        $a_order = Model_Fenxiao_Config::get_val('cfg_fenxiao_product_displayorder_'.$a['id'],0);
        $b_order = Model_Fenxiao_Config::get_val('cfg_fenxiao_product_displayorder_'.$b['id'],0);
        $a_order = empty($a_order)?99:$a_order;
        $b_order = empty($b_order)?99:$b_order;

        if($a_order==$b_order)
        {
            return 0;
        }
        return $a_order<$b_order?-1:1;


    }
}